package com.xbq.exceleditor.ui

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.gyf.immersionbar.ktx.immersionBar
import com.xbq.exceleditor.adapter.TemplateAdapter
import com.xbq.exceleditor.databinding.FragmentTemplatesBinding
import com.xbq.exceleditor.ui.excel.ExcelActivity
import com.xbq.exceleditor.utils.ensureCopyFile
import com.xbq.exceleditor.utils.ensureStoragePermission
import com.xbq.exceleditor.utils.ensureVip
import com.xbq.xbqsdk.component.activity.VBFragment
import com.xbq.xbqsdk.component.recyleview.GridSpaceDecoration
import dagger.hilt.android.AndroidEntryPoint
import java.util.*
import javax.inject.Inject

/**
 * Author: liaohaiping
 * Time: 2020-10-24
 * Description:
 */
@AndroidEntryPoint
class TemplatesFragment :
    VBFragment<FragmentTemplatesBinding>() {
    @Inject
    lateinit var templateAdapter:TemplateAdapter


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.adview.init("templates",requireActivity())
        initRecyclerView()
        loadTemplates()
    }

    private fun initRecyclerView() {
        binding.templateList.let {
            it.layoutManager = GridLayoutManager(context,2)
            it.addItemDecoration(GridSpaceDecoration(2,8f))
            it.adapter = templateAdapter
            templateAdapter.setOnItemClickListener { ad, view, position ->
                ensureVip("opentemplate") {
                    val item = templateAdapter.getItem(position)
                    val xlsxFile = requireContext().ensureCopyFile(item)
//                    TemplateDetailActivity.start(item)
                    ExcelActivity.startEdit(xlsxFile.absolutePath)
                }
            }
        }
    }

    private fun loadTemplates() {
        context?.let {
            val files = it.assets.list("templates")
            var results = arrayListOf<String>()
            files?.let {
                for (file in it) {
                    if (file.endsWith(".png")) {
                        results.add(file)
                    }
                }
            }
            results.shuffle(Random(it.packageName.hashCode().toLong()))
            templateAdapter.setList(results)
        }
    }

    override fun onResume() {
        super.onResume()
        immersionBar {
            fitsSystemWindows(true)
            statusBarDarkFont(true)
        }
    }
}